package org.Lin.server;

import org.Lin.util.AESUtil;
import org.Lin.util.DatabaseUtil;
import org.Lin.util.LogUtil;
import org.json.JSONObject;
import java.sql.*;

public class AdminServer {

    public static void handle(JSONObject json) {
        String adminID = json.getString("adminID");
        String operation = json.getString("operation");

        try (Connection conn = DatabaseUtil.getConnection()) {
            String checkSql = "SELECT is_super_admin FROM Admin WHERE adminID = ?";
            PreparedStatement checkStmt = conn.prepareStatement(checkSql);
            checkStmt.setString(1, adminID);
            ResultSet rs = checkStmt.executeQuery();

            if (!rs.next()) {
                JSONObject error = new JSONObject();
                error.put("type", "admin_error");
                error.put("message", "管理员不存在");
                NetworkServer.send(AESUtil.encrypt(error.toString()));
                return;
            }

            boolean isSuperAdmin = rs.getBoolean("is_super_admin");

            switch (operation) {
                case "delete_all_users":
                    if (!isSuperAdmin) {
                        sendError("权限不足");
                        return;
                    }
                    String deleteSql = "DELETE FROM User";
                    Statement stmt = conn.createStatement();
                    stmt.executeUpdate(deleteSql);
                    LogUtil.logOperation("Admin", "delete_all_users", "删除所有用户");
                    break;
                case "change_user_status":
                    String targetUserID = json.getString("targetUserID");
                    String newStatus = json.getString("newStatus");
                    String updateSql = "UPDATE User SET account_status = ? WHERE userID = ?";
                    PreparedStatement updateStmt = conn.prepareStatement(updateSql);
                    updateStmt.setString(1, newStatus);
                    updateStmt.setString(2, targetUserID);
                    updateStmt.executeUpdate();
                    LogUtil.logOperation("User", "change_status", "修改用户 " + targetUserID + " 状态为 " + newStatus);
                    break;
                default:
                    sendError("未知操作");
                    return;
            }

            JSONObject success = new JSONObject();
            success.put("type", "admin_operation_success");
            success.put("message", "操作成功");
            NetworkServer.send(AESUtil.encrypt(success.toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void sendError(String msg) throws Exception {
        JSONObject error = new JSONObject();
        error.put("type", "admin_error");
        error.put("message", msg);
        NetworkServer.send(AESUtil.encrypt(error.toString()));
    }
}
